package com.guet.careapp.controller.rest.controller.user;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.guet.careapp.common.Constants;
import com.guet.careapp.controller.rest.common.errorCode.Error;
import com.guet.careapp.controller.rest.common.errorCode.ErrorCode;
import com.guet.careapp.controller.rest.common.errorCode.ErrorCodeFactory;
import com.guet.careapp.pojo.TUserInfo;
import com.guet.careapp.pojo.rest.AjaxReturn;
import com.guet.careapp.service.IPushService;
import com.guet.careapp.service.IUserInfoService;
import com.guet.careapp.utils.CheckParams;
import com.guet.careapp.utils.ConvertUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * Created by LXM on 2017/10/13.
 *
 * @author LXM
 * @version 1.0
 * @description 关于用户的资源
 * @datetime 19:24
 */
@Controller
@Path("/user")
public class UsersController {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IPushService pushService;

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    /**
     * 登陆方法，传入格式：JSON，相应格式：JSON。
     *
     * @return 如果登陆成功，返回一个200的Error Code，如果密码错误，返回一个 的Error Code
     */
    @Path("/login")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String login(String json) {
        Map map = ConvertUtils.jsonToMap(json);
        Error error = userInfoService.login(map);
        ErrorCode errorCode = ErrorCodeFactory.get(error);
        //处理登陆逻辑
        return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
    }


    /**
     * 查询方法，响应格式：JSON。根据用户提供的uid。查询用户所有的信息。
     *
     * @param uid 每个用户唯一的编号
     * @return User
     */
    @Path("/{id}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String show(@PathParam("id") final String uid) {
        TUserInfo u;
        AjaxReturn ajaxReturn = new AjaxReturn();
        Map<String, Object> map = new HashMap<>();
        try {
            u = userInfoService.findById(Integer.parseInt(uid));
            map.put("u_id", u.getUId());
            map.put("username", u.getName());
            map.put("telphone", u.getTelphone());
            map.put("image", u.getImage());
            map.put("type", u.getType());
            map.put("register_time", u.getRegisTime());
            map.put("device_id", u.getDeviceId());
        } catch (Exception e) {
            ErrorCode errorCode = ErrorCodeFactory.get(Error.NotFond);
            ajaxReturn = new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning());
            return gson.toJson(ajaxReturn);
        }
        ajaxReturn.setCode(Constants.SUCCESS_CODE);
        ajaxReturn.setMsg(Constants.SUCCESS);
        ajaxReturn.setData(map);
        return gson.toJson(ajaxReturn);

    }


    /**
     * 搜索用户方法，通过切面检查权限，查询用户信息。用于添加监护人，查询监护人或被监护人信息等业务.
     *
     * @return json格式的用户信息
     * @ telphone      用户手机号码
     * @ u_id      用户id号码
     * @ name 用户名
     * @ device_id 设备id
     */
    @POST
    @Path("/search")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String showInfo(final String json) {
        AjaxReturn ajaxReturn = new AjaxReturn();
        List<TUserInfo> uList;
        Map map = ConvertUtils.jsonToMap(json);
        if (map.get("username") != null) {
            map.put("name", map.get("username"));
            map.remove("username");
        }
        List<Map> list = new ArrayList<>();
        //查找用户信息
        try {
            uList = userInfoService.findAllByField(map);
        } catch (Exception e) {
            ErrorCode errorCode = ErrorCodeFactory.get(Error.Invaild);
            ajaxReturn = new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning());
            return gson.toJson(ajaxReturn);
        }
        if (uList.size() == 0) {
            ErrorCode errorCode = ErrorCodeFactory.get(Error.NotFond);
            ajaxReturn = new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning());
            return gson.toJson(ajaxReturn);
        }
        for (TUserInfo u : uList) {
            map = new HashMap();
            map.put("u_id", u.getUId());
            map.put("username", u.getName());
            map.put("telphone", u.getTelphone());
            map.put("image", u.getImage());
            map.put("type", u.getType());
            map.put("register_time", u.getRegisTime());
            map.put("device_id", u.getDeviceId());
            list.add(map);
        }

        //调用服务层查询的接口，返回查询结果。注意，这个和查询所有信息不一样，不一定要求所有信息都展示出来
        ajaxReturn.setCode(Constants.SUCCESS_CODE);
        ajaxReturn.setMsg(Constants.SUCCESS);
        ajaxReturn.setData(list);
        return gson.toJson(ajaxReturn);
    }


    /**
     * 用户注册方法，用于注册业务中。
     *
     * @return ErrorCode 响应码
     * @ userName 用户名
     * @ password 密码
     * @ tel      电话号码
     * @ code     验证码，可以是短信验证码，也可以是邮件验证码。
     * @ device_id 极光推送绑定的设备号
     */
    @Path("/register")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String register(String json) {

        AjaxReturn ajaxReturn = new AjaxReturn();
        //解析Json
        Map map = ConvertUtils.jsonToMap(json);

        String tel = "" + map.get("telphone");
        String code = "" + map.get("verify_code");
        String username = "" + map.get("username");
        String psw = "" + map.get("password");
        String type = "" + map.get("type");
        String device = "" + map.get("device_id");

        if (CheckParams.isBlank(tel, code, username, psw, type)) {
            ErrorCode errorCode = ErrorCodeFactory.get(Error.IsBlank);
            ajaxReturn = new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning());
            return gson.toJson(ajaxReturn);
        }

        //检查用户是否验证码正确
        Error verifyError;
        try {
            verifyError = userInfoService.checkVerify(tel, code);
        } catch (Exception e) {
            ErrorCode errorCode = ErrorCodeFactory.get(Error.Invaild);
            ajaxReturn = new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning());
            return gson.toJson(ajaxReturn);
        }
        if (verifyError != Error.Success) {
            ErrorCode errorCode = ErrorCodeFactory.get(verifyError);
            ajaxReturn = new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning());
            return gson.toJson(ajaxReturn);
        }

        Error error = userInfoService.registe(username, psw, tel, type, device);
        ErrorCode errorCode = ErrorCodeFactory.get(error);
        ajaxReturn = new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning());
        return gson.toJson(ajaxReturn);
    }

    @Path("all")
    @Produces(MediaType.APPLICATION_JSON)
    @GET
    public String getAllUsers() {
        AjaxReturn ajaxReturn;
        List<Map> list = new LinkedList<>();
        List<TUserInfo> users = userInfoService.findAll();
        for (TUserInfo u : users) {

            Map map = new HashMap();
            map.put("u_id", u.getUId());
            map.put("username", u.getName());
            map.put("telphone", u.getTelphone());
            map.put("image", u.getImage());
            map.put("type", u.getType());
            map.put("register_time", u.getRegisTime());
            map.put("device_id", u.getDeviceId());
            list.add(map);
        }

        ajaxReturn = new AjaxReturn(Constants.SUCCESS_CODE, Constants.SUCCESS, list);
        return gson.toJson(ajaxReturn);
    }


    /**
     * 获取短信验证码的接口
     *
     * @param json
     * @return
     */
    @Path("/verification")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String sendVerifyCode(String json) {
        //解析Json
        Map map = ConvertUtils.jsonToMap(json);
        String tel = "" + map.get("telphone");
        Error e = userInfoService.askForVerifyCode(tel);
        ErrorCode errorCode = ErrorCodeFactory.get(e);

        return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));

    }

//    @Path("/xixixi")
////    @POST
////    @Consumes(MediaType.APPLICATION_JSON)
////    @Produces(MediaType.APPLICATION_JSON)
////    public ErrorCode xixixi(String uri) {
////
////        TInstruction instruction = new TInstruction();
////        instruction.setPara("{\n"
////            + "\t\n"
////            + "\t\"iNum\":\"1000\",\n"
////            + "\t\"description\":\"这是一条测试命令\",\n"
////            + "\t\"sendUid\":\"1\",\n"
////            + "\t\"receiveUid\":\"3\",\n"
////            + "\t\"content\":{\n"
////            + "\t\t\"x\":\"122.22222\",\n"
////            + "\t\t\"y\":\"43.454531\"\n"
////            + "\t}\n"
////            + "\t\n"
////            + "}");
////
////        Error w = pushService.PushMessage(instruction);
////        return ErrorCodeFactory.get(w);
////    }


    @Path("/info")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String changeInfo(String json) {

        //解析Json
        Map map = ConvertUtils.jsonToMap(json);
        Error error = userInfoService.changeInfo(map);
        ErrorCode errorCode = ErrorCodeFactory.get(error);

        return gson.toJson(new AjaxReturn(errorCode.getCodeNum(), errorCode.getMeanning()));
    }

}
